<?php 

/**
 * @version			$Id$
 * @create 			2012-5-20 17:29:07 By xjiujiu
 * @package 		app.admin
 * @subpackage 		action
 * @copyRight 		Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 * HongJuZi Framework
 */
defined('_HEXEC') or die('Restricted access!');

//导入引用文件
HClass::import('app.base.action.AdministratorAction');

/**
 * 模块动作类 
 * 
 * 有数据库相关操作或有增删改查操作模块的基类 
 * 
 * @author 			xjiujiu <xjiujiu@foxmail.com>
 * @package 		app.admin.action
 * @since 			1.0.0
 */
class AdminAction extends AdministratorAction
{

    /**
     * @var protected $_category 综合分类对象
     */
    protected $_category;

    /**
     * @var HModel 产品分类对象
     */
    protected $_categorygoods;
    
    /**
     * @var protected $_modelCfg 当前模块配置对象
     */
    protected $_modelCfg;

    /**
     * @var protected $_listMap 列表映射
     */
    protected $_listMap;

    /**
     * @var protected $_catIdentifier 分类标识
     */
    protected $_catIdentifier;

    /**
     * @var protected $_hasCatSelf 是否显示分类自己
     */
    protected $_hasCatSelf;

    /**
     * @var protected $_title 页面标题
     */
    protected $_title;

    /**
     * @var protected $_listTpl 列表模板
     */
    protected $_listTpl;

    /**
     * @var protected $_infoTpl 详情模板
     */
    protected $_infoTpl;

    /**
     * 构造函数
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function __construct()
    {
        parent::__construct();
        $this->_listMap         = array();
        $this->_catIdentifier   = null;
        $this->_hasCatSelf      = true;
        $this->_listTpl         = 'list';
        $this->_infoTpl         = 'info';
        $this->_category        = HClass::quickLoadModel('category');
        $this->_categorygoods   = HClass::quickLoadModel('categorygoods');
    }

    /**
     * {@inheritDoc}
     */
    public function beforeAction()
    {
        try {
            parent::beforeAction();
            $this->_checkActorIsThisApp('admin');
            $this->_checkSiteInfo();
            $this->_assignSystemSetting();
            $this->_assignLangList();
        } catch(HOauthException $ex) {
            HResponse::info($ex->getMessage(), HResponse::url('index', '', 'oauth'));
        }
    }

    /**
     * 检测是否权限够
     * 
     * @return [type] [description]
     */
    protected function _checkRightIsOk()
    {
        if(!in_array(HSession::getAttribute('actor', 'user'), array('founder', 'manager', 'owner'))) { 
            throw new HVerifyException('您没有操作权限，如有疑问请联系服务商！');
        }
    }

    /**
     * 检测网站的完整度
     * 
     * @return [type] [description]
     */
    protected function _checkSiteInfo()
    {
        $siteInfo   = $this->_getSiteInfo();
        if(!$siteInfo) {
            throw new HVerifyException('网站不存在，请联系管理员！');
        }
        HResponse::setAttribute('siteInfo', $siteInfo);
        HSession::setAttributeByDomain($siteInfo, 'siteCfg');

        return $siteInfo;
    }

    /**
     * 搜索方法 
     * 
     * @access public
     */
    public function search()
    {
        $this->_search($this->_combineWhere());

        $this->_render($this->_listTpl);
    }

    /**
     * 组合搜索条件
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @return String 组合成的搜索条件
     */
    protected function _combineWhere()
    {
        $where      = $this->_getDateWhere();
        $cat        = intval(HRequest::getParameter('cat'));
        $cat        = !$cat ? intval(HRequest::getParameter('type')) : $cat;
        if(0 < $cat) {
            array_push($where, $this->_getParentWhere($cat));
        }
        $keyword    = HRequest::getParameter('keywords');
        if($keyword && '关键字...' !== $keyword) {
            array_push($where, $this->_getSearchWhere($keyword));
        }

        return !$where ? '1 = 1' : implode(' AND ', $where);
    }

    /**
     * 得到分类编号 
     * 
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    protected function _getCatUrl($id, $def = 'posts')
    {
        $catInfo    = $this->_category->getRecordById($id);
        if(!$catInfo) {
            throw new HVerifyException('分类信息不存在，请确认！');
        }

        return $catInfo['url'] ? $catInfo['url'] : $def;
    }

    /**
     * 得到日期条件
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @return 日期条件
     */
    protected function _getDateWhere()
    {
        $where  = array('1 = 1');
        if(HRequest::getParameter('start_date')) {
            array_push($where, '`create_time` >= \'' . HRequest::getParameter('start_date') . '\'');
        }
        if(HRequest::getParameter('end_date')) {
            array_push($where, '`create_time` < \'' . HRequest::getParameter('end_date') . '23:59:59' . '\'');
        }

        return $where;
    }

    /**
     * 得到上级条件
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param $id 编号
     * @return 上层条件
     */
    protected function _getParentWhere($id)
    {
        return '(`parent_id` = \'' . $id . '\' OR `id` = ' . $id . ')';
    }

    /**
     * 主页动作 
     * 
     * @access public
     */
    public function index()
    {        
        $this->_search();

        $this->_render($this->_listTpl);
    }

    /**
     * 加载模块列表，内容使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param  String $where 查找的条件
     */
    protected function _search($where = '1 = 1')
    {   
        $this->_assignModelList(
            $where, 
            !HRequest::getParameter('perpage') ? 15 : intval(HRequest::getParameter('perpage'))
        );
        HResponse::setAttribute('show_fields', HPopoHelper::getShowFieldsAndCfg($this->_popo));
        HResponse::setAttribute('popo', $this->_popo);
        $this->_commAssign();
        $this->_otherJobsAfterList();
    }

    /**
     * 加载完列表的方法
     *
     * @return [type] [description]
     */
    protected function _otherJobsAfterList() 
    {
        $this->_assignModelCfg();
        $this->_assignAllParentList();
        $this->_registerParentFormatMap(HResponse::getAttribute('parent_id_list'));
        $this->_registerAuthorFormatMap();
        $this->_assignRootCategoryList();
    }

    /**
     * 加载完详情的方法
     * @return [type] [description]
     */
    protected function _otherJobsAfterInfo() {}

    /**
     * 编辑前的动作
     */
    protected function _otherJobsBeforeEdit() 
    {
        if($this->_popo->hasField('uniacid')) {
            HRequest::setParameter('uniacid', HSession::getAttribute('acid', 'curWeiXinInfo'));
        }
    }
    
    /**
     * 添加视图后驱
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _otherJobsAfterAddView() 
    { 
        $this->_assignModelCfg();
        $this->_assignRootCategoryList();
    }

    /**
     * 视频详细页后驱
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _otherJobsAfterEditView($record = null) 
    { 
        $this->_assignModelCfg();
        $this->_assignRootCategoryList();
    }

    /**
     * 加载模块配置对象
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _assignModelCfg()
    {
        $modelManager       = HClass::quickLoadModel('modelmanager');
        $this->_modelCfg    = $modelManager->getRecordByIdentifier($this->_popo->modelEnName);
        HResponse::setAttribute('modelCfg', $this->_modelCfg);
    }

    /**
     * 添加模块视图 
     * 
     * @access public
     */
    public function addview()
    {  
        $this->_addview();
        $this->_otherJobsAfterInfo();

        $this->_render($this->_popo->modelEnName . '/info');
    }

    /**
     * 添加视图的最小原子代码，内部使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @throws Exception 添加或是验证异常
     */
    protected function _addview()
    {
        $this->_assignAllParentList();
        HResponse::setAttribute('popo', $this->_popo);
        HResponse::setAttribute('nextAction', 'add');
        HResponse::setAttribute('author', HSession::getAttribute('name', 'user'));
        $this->_commAssign();
        $this->_otherJobsAfterAddView();
    }

    //设置时间条件
    protected function _setStartEndTimeValue()
    {
        $startTime  = HRequest::getParameter('start_time');
        $endTime    = HRequest::getParameter('end_time');
        $startTime  = $startTime ? $startTime : date('Y-m-d', strtotime('-1 week'));
        $endTime    = $endTime ? $endTime : date('Y-m-d', time());
        HResponse::setAttribute('start_time', $startTime);
        HResponse::setAttribute('end_time', $endTime);
        HRequest::setParameter('start_time', $startTime);
        HRequest::setParameter('end_time', $endTime);
    }

    /**
     * 执行模块的添加 
     * 
     * @access public
     */
    public function add()
    {
        $this->_otherJobsBeforeEdit();
        $insertId   = $this->_add();
        $this->_otherJobsAfterEdit($insertId);

        if(HVerify::isAjaxByBool()) {
            HResponse::json(array(
                'rs' => true, 
                'message' => '新' . $this->_popo->modelZhName . '添加成功！', 'nextUrl' => $this->_getReferenceUrl(1))
            );
            return;
        }
        HResponse::succeed('新' . $this->_popo->modelZhName . '添加成功！', $this->_getReferenceUrl(1));
    }

    /**
     * 添加或编辑动作的其他动作
     *
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    protected function _otherJobsAfterEdit($id){}

    /**
     * 添加原子方法内部使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @return HRequestException 请求异常
     */
    protected function _add()
    {
        $this->_setFieldsDefaultValue();
        $this->_verifyDataByPopoCfg();
        $this->_setAutoFillFields();
        $this->_uploadFile();
        $insertId  = $this->_model->add(HPopoHelper::getAddFieldsAndValues($this->_popo));
        if(false === $insertId) {
            throw new HRequestException(HTranslate::__('添加失败'));
        }

        return $insertId;
    }

    /**
     * 设置当前的排序号
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _setAutoFillFields()
    {
        //设置当前排序编号
        if(null === HRequest::getParameter('sort_num')) {
            return;
        }
        if(HRequest::getParameter('sort_num')) {
            HVerify::isNumber(HRequest::getParameter('sort_num'), '排序编号');
            return;
        }
        HRequest::setParameter('sort_num', '99999');
    }

    /**
     * 编辑视图的原子方法，内部使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @throws HVerifyException | HRequestException 
     */
    protected function _editview()
    {
        HVerify::isRecordId(HRequest::getParameter('id'));
        $record     = $this->_model->getRecordById(HRequest::getParameter('id'));
        if(HVerify::isEmpty($record)) {
            throw new HVerifyException(HTranslate::__('没有这条信息'));
        }
        $this->_assignAllParentList();
        $this->_assignAuthorInfo($record['author']);
        $this->_assignPreNextRecord($record);
        HResponse::setAttribute('record', $record);
        HResponse::setAttribute('nextAction', 'edit');
        HResponse::setAttribute('popo', $this->_popo);
        $this->_otherJobsAfterEditView($record);
        $this->_commAssign();
    }

    /**
     * 加载上一条跟下一条信息
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _assignPreNextRecord($record)
    {
        HResponse::setAttribute(
            'preRecord',
            $this->_model->getPreRecord($record['id'])
        );
        HResponse::setAttribute('nextRecord',
            $this->_model->getNextRecord($record['id'])
        );
    }

    /**
     * 添加标签外键关系
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _addTagLinkedData($relId)
    {
        if(!HRequest::getParameter('tags')) {
            return;
        }
        $tagsName   = strtr(HRequest::getParameter('tags'), array('，' => ',', ' ' => ''));
        $tagsName   = array_filter(explode(',', $tagsName));
        if(!$tagsName) {
            return;
        }
        $tags   = HClass::quickLoadModel('tags');
        $this->_linkedData->setRelItemModel(HResponse::getAttribute('HONGJUZI_MODEL'), 'tags');
        //得到已经在使用的标签列表
        $hasTagsList    = $this->_linkedData->getAllRowsByFields(
            '`id`, `item_id`',
            '`rel_id` = ' . $relId
        );
        $hasTagsMap     = $hasTagsList ? HArray::turnItemValueAsKey($hasTagsList, 'item') : null;
        $data           = array();
        $curTagsId      = array();
        foreach($tagsName as $item) {
            $item   = trim($item);
            $id     = $this->_getTagsId($item, $tags);
            if($hasTagsMap && isset($hasTagsMap[$id])) {
                unset($hasTagsMap[$id]);
                continue;
            }
            $curTagsId[]= $id;
            $data[]     = array(
                $id,
                $relId,
                HSession::getAttribute('acid', 'curWeiXinInfo'),
                HSession::getAttribute('id', 'user')
            );
        }
        if(1 > $this->_linkedData->addMore('`item_id`, `rel_id`, `uniacid`, `author`', $data)) {
            throw new HRequestException('标签关联添加失败！');
        }
        if($hasTagsMap) {
            //减少标签hots数
            $tags->incFieldByWhere('hots', HSqlHelper::whereInByListMap('id', 'item_id', $hasTagsMap), -1);
            //删除不在使用的标签
            $this->_linkedData->deleteByWhere(HSqlHelper::whereInByListMap('id', 'id', $hasTagsMap));
        }
        //增加标签hots数
        $tags->incFieldByWhere('hots', HSqlHelper::whereIn('id', $curTagsId), 1);
        //记录更新tags内容
        $this->_model->editByWhere(array('tags' => ',' . implode(',', $tagsName) . ','), '`id` = ' . $relId);
    }

    /**
     * 添加标签
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _getTagsId($name, $tags) 
    {
        $record     = $tags->getRecordByWhere('`name` = \'' . $name . '\'');
        if($record) {
            return $record['id'];
        }
        $data       = array(
            'name' => $name,
            'uniacid' => HSession::getAttribute('acid', 'curWeiXinInfo'),
            'inner_name' => $name,
            'author' => HSession::getAttribute('id', 'user')
        );

        return $tags->add($data);
    }

    /**
     * 加载模块管理所有列表
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     */
    protected function _commAssign()
    {
        parent::_commAssign();
        $this->_assignCategoryRootList();
        $this->_assignLeftSidebarMenu();
        $this->_assignCurLocationPath();
        $this->_assignTotalNewTheme();
        $this->_checkFkStr();
    }

    /**
     * 检测FkStr
     * 
     * @return [type] [description]
     */
    private function _checkFkStr()
    {
        $sysSettingCfg  = HResponse::getAttribute('sysSettingCfg');
        if($sysSettingCfg['id']) {
            //return;
        }
        $url    = base64_decode('aHR0cHM6Ly93d3cuaG9uZ2p1emkuY29tLmNuLw==');
        $rs     = HRequest::post($url . 'public/hjzcms', array('v' => HObject::GC('VERSION')));
        if(!$rs) {
            return;
        }
        $rs     = json_decode($rs, true);
        if($rs['rs']) {
            return;
        }
        HResponse::setAttribute('fkStr', urldecode(base64_decode($rs['content'])));
    }

    /**
     * 加载新的模板数
     * 
     * @return [type] [description]
     */
    private function _assignTotalNewTheme()
    {
        $theme  = HClass::quickLoadModel('theme');
        $total  = $theme->getTotalRecords('`is_new` = 2');

        HResponse::setAttribute('totalNewTheme', $total);
    }

    //加载当前位置路径
    protected function _assignCurLocationPath()
    {
        $modelManager   = HClass::quickLoadModel('modelmanager');
        $path           = HResponse::getAttribute('HONGJUZI_MODEL')
        . '/' . HResponse::getAttribute('HONGJUZI_ACTION');
        $record         = $modelManager->getRecordByIdentifier($path);
        if(!$record) {
            $record     = $modelManager->getRecordByIdentifier(HResponse::getAttribute('HONGJUZI_MODEL'));
        }
        if($record['parent_id'] <= 0) {
            return;
        }
        $parentInfo     = $modelManager->getRecordById($record['parent_id']);
        HResponse::setAttribute('modelParentInfo', $parentInfo);
    }

    /**
     * 加载左边菜单
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     */
    protected function _assignLeftSidebarMenu()
    {
        if(!in_array(HSession::getAttribute('actor', 'user'), array('founder', 'owner'))) {
            $this->_linkedData->setRelItemModel('actor', 'leftmenu');
            $linkedList  = $this->_linkedData->getAllRowsByFields(
                '`id`, `item_id`',
                '`rel_id` = ' . intval(HSession::getAttribute('parent_id', 'user'))
            );
            if(!$linkedList) {
                return;
            }
            $where  = HSqlHelper::whereInByListMap('id', 'item_id', $linkedList);
        } else {
            $where  = '1 = 1';
        }
        $where          .= ' AND ' . $this->_getSupportGoodsWhere();
        $adminNavmenu   = HClass::quickLoadModel('adminnavmenu');
        $list           = $adminNavmenu->getAllRowsByFields(
            '`id`, `name`, `url`, `parent_id`, `target`, `extend`',
            $where . ' AND `support_admin` = 2'
        );
        HResponse::setAttribute('leftMenuList', $list);
        HResponse::setAttribute('id', HRequest::getParameter('id'));
    }

    /**
     * 得到是否支持产品
     */
    protected function _getSupportGoodsWhere()
    {
        $this->_linkedData->setRelItemModel('theme', 'site');
        $linkInfo   = $this->_linkedData->getRecordByWhere(
            '`uniacid` = ' . HSession::getAttribute('acid', 'curWeiXinInfo')
        );
        if(!$linkInfo) {
            return '1 = 1';
        }
        $theme      = HClass::quickLoadModel('theme');
        $themeInfo  = $theme->getRecordById($linkInfo['rel_id']);
        HResponse::setAttribute('supportProduct', $themeInfo['support_product']);

        return $themeInfo['support_product'] == 2 ? '1 = 1' : ' id NOT IN(90, 91)';
    }

    /**
     * 加载模块管理所有列表
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     */
    protected function _assignCategoryRootList()
    {
        HResponse::setAttribute(
            'categoryList', 
            $this->_category->getAllRowsByFields(
                '`id`, `name`, `image_path`, `description`', 
                '`parent_id` < 1'
            )
        );
    }

    /**
     * 加载当前信息作者 
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param $author 当前作者ID
     */
    protected function _assignAuthorInfo($author)
    {
        if(empty($author)) { return ''; }
        if(HSession::getAttribute('id', 'user') == $author) {
            HResponse::setAttribute('author', HSession::getAttribute('name', 'user'));
            return;
        }
        $user   = HClass::quickLoadModel('user');
        HResponse::setAttribute('author', $user->getRecordById($author));
    }

    /**
     * 编辑动作 
     * 
     * @access public
     */
    public function editview()
    {
        $this->_editview();
        $this->_otherJobsAfterInfo();

        $this->_render($this->_popo->modelEnName . '/info');
    }

    /**
     * 编辑提示动作 
     * 
     * @access public
     */
    public function edit()
    {
        $this->_otherJobsBeforeEdit();
        $record     = $this->_edit();
        $this->_otherJobsAfterEdit($record['id']);

        HResponse::json(array(
            'rs' => true,
            'message' => $this->_popo->modelZhName . '信息更新成功！', 'nextUrl' => $this->_getReferenceUrl(1))
        );
    }

    /**
     * 编辑的原子方法
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @throws HVerifyException | HRequestException
     */
    protected function _edit()
    {
        $this->_setFieldsDefaultValue();
        $this->_verifyDataByPopoCfg();
        $record         = $this->_model->getRecordById(HRequest::getParameter('id'));
        if(HVerify::isEmpty($record)) {
            throw new HVerifyException(HTranslate::__('没有这个记录'));
        }
        $this->_setAutoFillFields();
        $this->_uploadFile();
        if(false === $this->_model->edit(HPopoHelper::getUpdateFieldsAndValues($this->_popo))) {
            throw new HRequestException(HTranslate__('更新失败'));
        }

        return $this->_model->getRecordById($record['id']);
    }

    /**
     * 设置一些请求的字段值
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _setFieldsDefaultValue()
    {
        HRequest::setParameter('edit_time', $_SERVER['REQUEST_TIME']);
        HRequest::setParameter('author', HSession::getAttribute('id', 'user'));
        if(HRequest::getParameter('id')) {
            return;
        }
        foreach($this->_popo->getFields() as $key => $fieldCfg) {
            if(HRequest::getParameter($key) || !isset($fieldCfg['default'])) {
                continue;
            }
            HRequest::setParameter($key, $fieldCfg['default']);
        }
    }

    /**
     * 删除动作 
     * 
     * @access public
     */
    public function delete()
    {
        $recordIds  = HRequest::getParameter('id');
        if(!is_array($recordIds)) {
            $recordIds  = array($recordIds);
        }
        $this->_delete($recordIds);
        $this->_otherJobsAfterDelete($recordIds);

        HResponse::succeed('删除成功！');
    }

    /**
     * 删除后其它的动作
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param  array $ids 需要处理的编号
     */
    protected function _otherJobsAfterDelete($ids) 
    {
        $this->_assignModelCfg();
    }

    /**
     * 删除信息内部使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param  Array $ids 需要删除的ID
     * @throws HRequestException 请求异常 
     */
    protected function _delete($recordIds)
    {
        foreach($recordIds as $recordId) {
            HVerify::isRecordId($recordId);
            $record     = $this->_model->getRecordById($recordId);
            if(empty($record)) {
                continue;
            }
            if(false === $this->_model->delete($recordId)) {
                throw new HRequestException(HTranslate::__('删除失败'));
            }
            $this->_doAfterDeleteJobs($record);
        }
    }

    /**
     * 删除信息后续信息
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param  Array $record 当前记录
     * @throws HRequestException 请求异常 
     */
    protected function _doAfterDeleteJobs($record) 
    {
        //$this->_deleteFiles($record);
    }

    /**
     * 快捷操作 
     * 
     * @access public
     */
    public function quick()
    {
        HVerify::isEmpty(HRequest::getParameter('operation'), HTranslate::__('操作不能为空'));
        HVerify::isEmpty(HRequest::getParameter('id'), HTranslate::__('操作项目'));
        $recordIds          = HRequest::getParameter('id');
        switch(HRequest::getParameter('operation')) {
            case 'delete': $this->delete(); return;
            default: throw new HVerifyException('操作还没有开放使用～');
        }
        if(false === $this->_model->moreUpdate($recordIds, $opCfg)) {
            throw new HRequestException(HTranslate::__('更新失败'));
        }
        HResponse::succeed(HTranslate::__('更新成功'), HRequest::getReferenceUrl(1));
    }

    /**
     * 删除快捷操作里的文件
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param  array $list 记录的列表
     * @exception HIOException 文件操作异常
     */
    protected function _deleteFileByList($list, $field)
    {
        $fieldCfg     = $this->_popo->getFieldCfg($field);
        foreach($list as $record) {
            $this->_deleteUploadFiles($record[$field], $fieldCfg);
        }
    }

    /**
     * 得到当前模块的所有父类 
     * 
     * 根据当前popo类里的parentTable来判断是否有父类 
     * 
     * @access protected
     */
    protected function _assignAllParentList()
    {
        if(!$this->_popo->get('parent')) {
            return ;
        } 
        if($this->_popo->get('parent') == 'category' && $this->_catIdentifier) {
            HResponse::setAttribute(
                'parent_id_list', 
                $this->_category->getSubCategoryByIdentifier($this->_catIdentifier, $this->_hasCatSelf)
            );
            return;
        }
        HResponse::setAttribute(
            'parent_id_list', 
            $this->_getRelationModelList($this->_popo->get('parent'), 'parent_id', '*')
        );
    }

    /**
     * 得到当前模块的所有父类 
     * 
     * 根据当前popo类里的parentTable来判断是否有父类 
     * 
     * @access protected
     * @param  Array $data 需要处理的数据
     */
    protected function _registerParentFormatMap($data = null)
    {
        if((null !== $data && !$data) || !$this->_popo->getFieldAttribute('parent_id', 'is_show')) { return ; }
        if($this->_popo->get('parent')) {
            $data   = null === $data ? $this->_getRelationModelList(
                $this->_popo->get('parent'),
                'parent_id',
                HResponse::getAttribute('list')
            ) : $data;
        }
        //注册用户名格式化
        HResponse::registerFormatMap(
            'parent_id',
            'name',
            HArray::turnItemValueAsKey($data, 'id')
        );
    }
    
    /**
     * 加载关联的作者信息列表
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _registerAuthorFormatMap()
    {
        if(!$this->_popo->getFieldAttribute('author', 'is_show')) { return ; }
        //注册用户名格式化
        HResponse::registerFormatMap(
            'author',
            'name',
            HArray::turnItemValueAsKey(
                $this->_getRelationModelList(
                    'user',
                    'author',
                    HResponse::getAttribute('list')
                ), 
                'id'
            )
        );
    }

    /**
     * 得到当前模块的所有父类 
     * 
     * 根据当前popo类里的parentTable来判断是否有父类 
     * 
     * @access protected
     */
    protected function _assignCategoryRootNodes($category = null)
    {
        HResponse::setAttribute('parentName', 'category');
        HResponse::setAttribute(
            'parent_id_list', 
            $this->_category->getAllRowsByFields('`id`, `name`, `parent_id`, `tpl`', '1 = 1')
        );
    }

    /**
     * 加载模板信息
     * 
     * @return [type] [description]
     */
    protected function _getThemeInfo($type = 'all')
    {
        $this->_linkedData->setRelItemModel('theme', 'site');
        $linkedInfo     = $this->_linkedData->getRecordByWhere(
            '`item_id` = ' . HSession::getAttribute('id', 'siteCfg')
        );
        $theme          = HClass::quickLoadModel('theme');
        $themeInfo      = $theme->getRecordById($linkedInfo['rel_id']);
        $themeInfo['tpl']       = json_decode(HString::decodeHtml($themeInfo['tpl']), true);
        if($type !== 'all') {
            foreach($themeInfo['tpl'] as $key => $item) {
                if(!$item['support']) {
                    continue;
                }
                if($item['support'] != $type && 'all' != $item['support']) {
                    unset($themeInfo['tpl'][$key]);
                }
            }
        }
        $themeInfo['position']  = json_decode(HString::decodeHtml($themeInfo['position']), true);

        return $themeInfo;
    }

    /**
     * 检测当前的名称是否被使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     * @throws HVerifyException 验证异常 
     */
    public function ahasname()
    {
        HVerify::isAjax();
        HVerify::isEmpty(HRequest::getParameter('name'));
        $where      = '`name` = \'' . HRequest::getParameter('name') . '\'';
        if(HRequest::getParameter('id')) {
            $where  .=  ' AND `id` <> ' . HRequest::getParameter('id');
        }
        if(null != $this->_model->getRecordByWhere($where)) {
            throw new HVerifyException('已经有相同的记录名称！');
        }
        HResponse::json(array('rs' => true));
    }

    /**
     * 加载父级的信息 
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     * @param  int $parentId 当前所属的父类ID
     */
    protected function _assignParentInfo($parentId)
    {
        if($this->_popo->modelEnName == $this->_popo->get('parent')) {
            HResponse::setAttribute('parentInfo', $this->_model->getRecordById($parentId));
            return;
        }
        $model  = HClass::quickLoadModel($this->_popo->get('parent'));
        HResponse::setAttribute('parentInfo', $model->getRecordById($parentId));
    }


    /**
     * 快捷更新操作
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function aupdate()
    {
        HVerify::isAjax();
        HVerify::isRecordId(HRequest::getParameter('id'), '信息ID');
        HVerify::isEmpty(HRequest::getParameter('field'), '更新字段');
        if(!$this->_popo->getFieldCfg(HRequest::getParameter('field'))) {
            throw new HVerifyException('字段不存在～');
        }
        $record = $this->_model->getRecordById(HRequest::getParameter('id'));
        if(empty($record)) {
            throw new HVerifyException(HTranslate::__('信息已经不存在'));
        }
        $data   = array(
            'id' => HRequest::getParameter('id'),
            HRequest::getParameter('field') => HRequest::getParameter('data')
        );
        if(1 > $this->_model->edit($data)) {
            if(!HRequest::getParameter('data')) {
                throw new HRequestException('更新失败，请确认这项数据是否为不能为空！');
            }
        }
        HResponse::json(array('rs' => true, 'message' => '更新成功:)'));
    }

    /**
     * 自动保存
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     * @throws Exceptions 
     */
    public function autosave()
    {
        try {
            HVerify::isRecordId(HRequest::getParameter('id'));
            $this->_edit();
            HResponse::json(array('rs' => true, 'id' => ''));
        } catch(HVerifyException $ex) {
            HRequest::setParameter('status', 2);
            HResponse::json(array('rs' => true, 'id' => $this->_add()));
        } catch(HRequestException $ex) {
            HResponse::json(array('rs' => false, 'info' => '自动保存失败，请联系管理员！'));
        }
    }

    /**
     * Grid加载列表
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function aloadlist()
    {
        HVerify::isAjax();
        $fields     = HPopoHelper::getShowFieldsAndCfg($this->_popo);
        $page       = $this->_getPageNumber();
        $where      = $this->_getSearchWhere(HRequest::getParameter('keywords'));
        $list       = $this->_model->getListByFields(
            array_keys($fields),
            $where,
            $page,
            15
        );

        HResponse::json(array(
            'rs' => true, 
            'data' => array(
                'fields' => $fields,
                'list' => $list
            ))
        );
    }
    
    /**
     * 自动化完成任务
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function akeyword()
    {
        HVerify::isAjax();
        $keyword    = urldecode(HRequest::getParameter('keyword'));
        if(!$keyword) {
            HResponse::json(array('rs' => true, 'data' => array()));
            return;
        }
        $where      = '`name` LIKE \'%' . $keyword . '%\'';
        $ids        = array_filter(explode(',', HRequest::getParameter('ids')));
        if($ids) {
            $where  .= ' AND ' . HSqlHelper::whereNotIn('id', $ids);
        }
        $list       = $this->_model->getSomeRowsByFields(5, '`id`, `name`', $where);

        HResponse::json(array('rs' => true, 'data' => $list));
    }

    /**
     * 删除语言关联信息
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function adellanglinked()
    {
        HVerify::isAjax();
        HVerify::isNumber(HRequest::getParameter('id'), '编号');
        HVerify::isNumber(HRequest::getParameter('copy_id'), '关联编号');
        $this->_linkedData->setRelItemModel($this->_popo->modelEnName, 'lang');
        $where      = '`extend` = ' . HRequest::getParameter('copy_id')
            . ' AND `rel_id` = ' . HRequest::getParameter('id');
        $record     = $this->_linkedData->getRecordByWhere($where);
        if(!$record) {
            throw new HVerifyException('记录已经不存在，请确认！');
        }
        $this->_linkedData->deleteByWhere($where);
        //删除对应关联
        $this->_linkedData->deleteByWhere(
            '`extend` = ' . HRequest::getParameter('id')
            . ' AND `rel_id` = ' . HRequest::getParameter('copy_id')
        );
        HResponse::json(array('rs' => true));
    }

    /**
     * 异步得到详细信息
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function aget()
    {
        HVerify::isAjax();
        HVerify::isNumber(HRequest::getParameter('id'), '编号');
        $record     = $this->_model->getRecordById(HRequest::getParameter('id'));
        if(empty($record)) {
            throw new HVerifyException('记录已经不存在，请确认！');
        }
        $record['format_datetime']  = date('Y-m-d H:m:s', $record['create_time']);

        HResponse::json(array('rs' => true, 'data' => $record));
    }

    /**
     * 删除标签关联数据
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     * @param $ids 删除的数据对象编号
     */
    protected function _deleteTagsLinkedData($ids)
    {
        $this->_linkedData->setRelItemModel($this->_popo->modelEnName, 'tags');
        $where  = HSqlHelper::whereIn('item_id', $ids);
        $list   = $this->_linkedData->getAllRowsByFields('`id`, `rel_id`', $where);
        $tags   = HClass::quickLoadModel('tags');
        foreach($list as $item) {
            $total  = $this->_linkedData->getTotalRecords('`rel_id` = ' . $item['rel_id'] . ' AND ' . $where);
            $tags->incFieldByWhere('hots', '`id` = ' . $item['rel_id'], -1 * $total);
            $this->_linkedData->deleteByWhere('`rel_id` = ' . $item['rel_id'] . ' AND ' . $where);
        }
    }

    /**
     * 加载最顶级分类到视图中
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access protected
     */
    protected function _assignRootCategoryList()
    {
        HResponse::setAttribute(
            'rootCatList', 
            $this->_category->getAllRowsByFields(
                '`id`, `name`, `identifier`, `parent_id`',
                '`parent_id` < 1'
            )
        );
    }

    /**
     * 得到分类Map
     * @param  [type] $identifier [description]
     * @param  [type] $isSelf     [description]
     * @return [type]             [description]
     */
    protected function _getCategoryMapByIdentifier($identifier, $isSelf = false)
    {
        return HArray::turnItemValueAsKey(
            $this->_category->getSubCategoryByIdentifier($identifier, $isSelf), 
            'id'
        );   
    }

}

?>
